package com.com.typhoon.dao;

import com.com.typhoon.entity.Permission;
import com.com.typhoon.entity.Role;
import com.com.typhoon.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/29 下午9:42
 * @description
 * @modified by
 * @since V2.0.0
 */
@Repository
@Slf4j
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User findByUsername(String username) {
        List<User> list = this.jdbcTemplate.query("select * from User where username = ?", BeanPropertyRowMapper.newInstance(User.class),username);
        if(null == list || list.isEmpty()) {
            return null;
        }
        User user = list.get(0);
        String roleSql = "select r.* from Role r left join UserOfRole uor on r.id = uor.roleId where uor.userId = ?";
        List<Role> roleList = this.jdbcTemplate.query(roleSql,BeanPropertyRowMapper.newInstance(Role.class),user.getId());
        if(null == roleList || roleList.isEmpty()) {
            return user;
        }
        user.setRoles(roleList);
        return user;
    }

}
